package cn.cqautotest.cqviehelper.ui.fragment;

import android.annotation.SuppressLint;
import android.os.Build;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.cqautotest.cqviehelper.R;
import cn.cqautotest.cqviehelper.base.BaseActivity;
import cn.cqautotest.cqviehelper.base.BaseFragment;
import cn.cqautotest.cqviehelper.base.BaseFragmentAdapter;
import cn.cqautotest.cqviehelper.utils.LogUtils;
import cn.cqautotest.cqviehelper.utils.ViewPager2Util;

@SuppressLint("NonConstantResourceId")
public class HomeFragment extends BaseFragment<BaseActivity> {

    private final List<BaseFragment<BaseActivity>> mFragments = new ArrayList<>();
    private final List<String> mTitles = new ArrayList<>();
    @BindView(R.id.homeTabLayout)
    TabLayout mHomeTabLayout;
    @BindView(R.id.homeViewPager2)
    ViewPager2 mHomeViewPager2;
    private TabLayoutMediator mTabLayoutMediator;
    private BaseFragmentAdapter mAdapter;

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView(View rootView) {
        mAdapter = new BaseFragmentAdapter(getAttachActivity());
        ViewPager2Util.changeToNeverMode(mHomeViewPager2);
        mHomeViewPager2.setUserInputEnabled(true);
        mHomeViewPager2.setAdapter(mAdapter);
        mTabLayoutMediator = new TabLayoutMediator(mHomeTabLayout, mHomeViewPager2, (tab, position) -> {
            if (position >= mTitles.size()) {
                LogUtils.d(this, "下标越界啦！");
                return;
            }
            tab.setText(mTitles.get(position));
        });
        mTabLayoutMediator.attach();
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void initData() {
        addFragmentAndTitle(new SchoolCalendarFragment(), "校历");
        addFragmentAndTitle(new MenuFragment(), "工程风景");
        mAdapter.setFragments(mFragments);
    }

    /**
     * 添加Fragment和对应的Title
     *
     * @param fragment
     * @param title
     */
    private void addFragmentAndTitle(BaseFragment<BaseActivity> fragment, String title) {
        mFragments.add(fragment);
        mTitles.add(title);
    }

    @Override
    protected void release() {
        if (mTabLayoutMediator != null) {
            mTabLayoutMediator.detach();
            mTabLayoutMediator = null;
        }
    }
}
